<?php
declare(strict_types=1);

namespace App\Service;

use App\Constants\XZXResponseCode;
use App\Exception\XZXValidationException;
use App\Model\Dao\TradeOrderDetailDao;
use App\Model\Dao\TradeOrderForceSuccessSingleDao;
use App\Utils\CustomUtils;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;


class TradeOrderForceSuccessSingleService
{

    /**
     * @Inject()
     * @var TradeOrderDetailDao
     */
    private $TradeOrderDetailDao;

    /**
     * @Inject()
     * @var TradeOrderForceSuccessSingleDao
     */
    private $TradeOrderForceSuccessSingleDao;

    public function add($param)
    {
        // 订单
        $detail = $this->TradeOrderDetailDao->getByTradeNo($param['tradeNo']);
        if (empty($detail)) {
            throw new XZXValidationException("找不到订单");
        }
        if ($detail['transStatus'] == 6) {
            throw new XZXValidationException("支付失败且为结算的订单才能操作");
        }
        $isForceSuccess = $this->TradeOrderForceSuccessSingleDao->getByOrderId($detail['id']);
        if (!empty($isForceSuccess)) {
            throw new XZXValidationException("已发起补单，请勿重复操作");
        }

        $data['id']            = CustomUtils::createUUID();
        $data['orderId']       = $detail['id'];
        $data['tradeNo']       = $detail['tradeNo'];
        $data['mchId']         = $detail['mchId'];
        $data['mchNo']         = $detail['mchNo'];
        $data['transAmount']   = $detail['settleAmount'];
        $data['transReason']   = $param['transReason'];
        $data['createBy']      = $param['createBy'];
        $data['createTime']    = time();
        $data['updateBy']      = $param['createBy'];

        Db::beginTransaction();
        try {
            $this->TradeOrderForceSuccessSingleDao->insert($data);

            $this->TradeOrderDetailDao->update($detail['id'], ['forceSuccessStatus' => 1]);
        } catch (\Throwable $th) {
            CustomUtils::xzxDebug($th->getMessage());
            Db::rollBack();
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::ADD_FAIL));
        }
        Db::commit();

        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),CustomUtils::xzxEmptyObject());
    }
}